package com.treasure.hunt.mine

import android.app.Activity
import android.content.Intent
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.module.lemlin.base.loadCircleImage
import com.module.lemlin.custom.SpacingItemDecoration
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.module.lemlin.util.qqShareImage
import com.module.lemlin.util.wxShareImage
import com.treasure.hunt.R
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.entity.Buddy
import com.treasure.hunt.getDiskCacheDirectoryImage
import com.treasure.hunt.mode.OtherViewMode
import com.treasure.hunt.popup.DialogSharePopup
import kotlinx.android.synthetic.main.activity_mine_buddy.*
import rxhttp.RxHttp


class MineBuddyActivity : ViewModeActivity<OtherViewMode>() {

    companion object {
        fun open(activity: Activity) {
            val intent = Intent(activity, MineBuddyActivity::class.java)
            activity.startActivity(intent)
        }
    }

    private val buddyAdapter:BaseQuickAdapter<Buddy, BaseViewHolder> =
        object : BaseQuickAdapter<Buddy, BaseViewHolder>(R.layout.item_mine_buddy) {
            override fun convert(holder: BaseViewHolder, item: Buddy) {
                val isHttps: Boolean = item.avatar.substring(0, 5).contains("http") ||
                        item.avatar.substring(0, 5).contains("https")
                holder.setText(R.id.tvBuddyNickname, item.nickname)
                    .getView<ImageView>(R.id.ivBuddyImage)
                    .loadCircleImage("${if (isHttps) "" else AppConstance.URL_IMAGE}${item.avatar}")
            }
        }

    private var shareType: Int = 1

    private val sharePopup: DialogSharePopup by lazy {
        DialogSharePopup(context = this) { view ->
            when (view.id) {
                R.id.tvDialogShareWX -> shareType = 1
                R.id.tvDialogShareQQ -> shareType = 2
            }
            viewModel.otherShareImage(2)
        }
    }

    override val layoutResId: Int
        get() = R.layout.activity_mine_buddy

    override fun viewModel(): OtherViewMode {
        return createViewModel()
    }

    override fun stateBar(): StatusBar {
        return StatusBar(
            isLightMode = false,
            bottomColor = R.color.FF_020027,
            view = flMineBuddyBar
        )
    }

    override fun initView() {
        ivMineBuddyBack.setOnClickListener {
            finish()
        }

        tvMineBuddyStart.setOnClickListener {
            sharePopup.showPopupWindow()
        }

        rvMineBuddyRecordBody.apply {
            val decoration = SpacingItemDecoration(
                vGap = ConvertUtils.dp2px(15f),
                hGap = ConvertUtils.dp2px(15f)
            )
            addItemDecoration(decoration)
        }.adapter = buddyAdapter.apply {
            setEmptyView(R.layout.dialog_load_style_2)
        }


        mSmartRefreshHeader.setColorSchemeResources(R.color.colorMain)
        mSmartRefreshLayout.setEnableLoadMore(false)
        mSmartRefreshLayout.setOnRefreshListener {
            viewModel.otherGetFriendsList()
        }
    }

    override fun initData() {
        viewModel.otherGetFriendsList()
    }

    override fun initViewMode() {

        viewModel.buddyListLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.throwable?.msg ?: "未知錯誤")
                mSmartRefreshLayout.finishRefresh()
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            mSmartRefreshLayout.finishRefresh()
            val buddyList: MutableList<Buddy>? = response.httpData?.data
            if (buddyList.isNullOrEmpty()) {
                buddyAdapter.setEmptyView(createErrorView("暂无数据~"))
            } else {
                buddyAdapter.setNewInstance(buddyList)
            }
        })

        viewModel.otherUrlLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let { image ->
                if (image.url.isNullOrEmpty()) {
                    toast("分享图片地址为空")
                } else {
                    val isHttps: Boolean = image.url.substring(0, 5).contains("http") ||
                            image.url.substring(0, 5).contains("https")
                    RxHttp.get("${if (isHttps) "" else AppConstance.URL_IMAGE}${image.url}")
                        .asDownload("${getDiskCacheDirectoryImage(this).path}/share.png")
                        .subscribe({
                            runOnUiThread {
                                if (shareType == 1) {
                                    wxShareImage(it)
                                }
                                if (shareType == 2) {
                                    qqShareImage(this, it)
                                }
                            }
                        }, {
                            toast(it.msg)
                        })
                }
            }
        })
    }

    private fun createErrorView(message: String? = null): View {
        return layoutInflater.inflate(R.layout.view_empty_error, null).apply {
            if (message != null)
                findViewById<TextView>(R.id.tvEmptyMessage).text = message
        }
    }
}